import View from 'ol/View'
import './style.css'
import 'ol/ol.css'
import Map from 'ol/Map'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'

const target = 'map'

const view = new View({
    center: [114.3165, 30.5953],
    zoom: 10,
    projection: 'EPSG:4326'
})

const tileLayer = new TileLayer({
    source: new XYZ({
        url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}'
    })
})


const map = new Map({
    target,
    view,
    layers: [tileLayer]
})

// 添加点击按钮
const [btn1, btn2, btn3, btn4, btn5] = document.querySelectorAll('.btn button')


btn1.addEventListener('click', () => {
    // 去北京
    // view.setCenter([116.407395, 39.904211])
    // 添加动画
    view.animate({
        center: [116.407395, 39.904211],
        zoom: 6,
        duration: 2000 // 设置动画的时间
    })
})

// 设置经纬度
const setCenter = (direction = 'up') => {
    let [x, y] = view.getCenter()
    const directionMap = {
        'up': () => y += 0.1,
        'down': () => y -= 0.1,
        'left': () => x -= 0.1,
        'right': () => x += 0.1
    }
    directionMap[direction]()
    view.setCenter([x, y])
    map.render() // 重新渲染地图
}

btn2.addEventListener('click', () => setCenter('up'))
btn3.addEventListener('click', () => setCenter('down'))
btn4.addEventListener('click', () => setCenter('left'))
btn5.addEventListener('click', () => setCenter('right'))